// Copyright 2006 Bret Taylor
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may
// not use this file except in compliance with the License. You may obtain
// a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
// License for the specific language governing permissions and limitations
// under the License.

#include <fstream>

#include "compiler.h"
#include "astprinter.h"
#include "checker.h"
#include "emitter.h"
#include "parser.h"

namespace indie {

Compiler::Compiler(Log& log) : log_(log) {
}

Compiler::~Compiler() {
}

void Compiler::Compile(const set<string>& files, ostream& output) {
    Checker checker(log_);
    auto_collection_ptr<set<AstFile*> > asts(Parse(files));
    checker.Check(*asts);

    if (!log_.has_errors()) {
	Emitter emitter;
	emitter.Emit(*asts);
    }
}

set<AstFile*>* Compiler::Parse(const set<string>& files) {
    Parser parser(log_);
    auto_collection_ptr<set<AstFile*> > asts(new set<AstFile*>);
    for (set<string>::iterator i = files.begin(); i != files.end(); ++i) {
	std::ifstream file(i->c_str());
	AstFile* ast = parser.Parse(*i, file);
	if (ast != NULL) asts->insert(ast);
	file.close();
    }
    return asts.release();
}

void Compiler::Check(const set<string>& files) {
    auto_collection_ptr<set<AstFile*> > asts(Parse(files));
    Checker checker(log_);
    checker.Check(*asts);
}

void Compiler::PrintAst(const set<string>& files, ostream& output) {
    AstPrinter printer;
    auto_collection_ptr<set<AstFile*> > asts(Parse(files));
    for (set<AstFile*>::iterator i = asts->begin(); i != asts->end(); ++i) {
	printer.Print(**i, output);
    }
}

}
